package com.kuang.utils;

import com.kuang.pojo.Content;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class HtmlParseUtil {

//    public static void main(String[] args) throws Exception {
//        new HtmlParseUtil().parseJd("vue").forEach(System.out::println);
//    }

    public List<Content> parseJd(String keywords) throws Exception {
        //获取请求，解析网页https://search.jd.com/Search?keyword=java
        //需要联网
        String url = "https://search.jd.com/Search?keyword="+keywords;
        //解析网页jsoup返回的document就是浏览器的Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有在js中的方法都能用
        Element element = document.getElementById("J_goodsList");
//        System.out.println(element.html());
        Elements elements = element.getElementsByTag("li");
        List<Content> goodsList = new ArrayList<>();
        for (Element el : elements) {
            //关于这种图片特别多的网站图片都是延迟加载的
//            String img = el.getElementsByTag("img").eq(0).attr("src");
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            Content content = new Content();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);
            goodsList.add(content);


        }
        return goodsList;
    }




}
